<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
        <el-form-item label="模板名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入模板名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="模板类型" prop="type">
          <el-select v-model="queryParams.type" placeholder="请选择模板类型" clearable>
            <el-option
            v-if="dict.type && dict.type.certificate_template_type"
            v-for="dict in dict.type.certificate_template_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option label="启用" value="启用" />
          <el-option label="禁用" value="禁用" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Upload"
          @click="handleUpload"
        >上传模板</el-button>
      </el-col>
      <right-toolbar v-model:show-search="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="templateList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="模板ID" align="center" prop="id" />
      <el-table-column label="模板名称" align="center" prop="name" :show-overflow-tooltip="true" />
        <el-table-column label="模板类型" align="center" prop="type">
          <template #default="scope">
          <dict-tag v-if="dict.type && dict.type.certificate_template_type" :options="dict.type.certificate_template_type" :value="scope.row.type"/>
          <span v-else>{{ scope.row.type }}</span>
          </template>
        </el-table-column>
      <el-table-column label="模板格式" align="center" prop="templateFormat" />
      <el-table-column label="版本号" align="center" prop="version" />
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="启用"
            inactive-value="禁用"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
          </template>
        </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button
              link
              icon="Edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
            <el-button
              link
              icon="Delete"
              @click="handleDelete(scope.row)"
            >删除</el-button>
          <el-dropdown @command="(command) => handleCommand(command, scope.row)">
            <span class="el-dropdown-link">
              <el-button link>更多<el-icon><arrow-down /></el-icon></el-button>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="template-editor" icon="Document">模板编辑与导出</el-dropdown-item>
                <el-dropdown-item command="variables" icon="Setting">变量配置</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />

    <!-- 添加或修改证书模板对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="模板类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择模板类型">
            <el-option
              v-if="dict.type && dict.type.certificate_template_type"
              v-for="dict in dict.type.certificate_template_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="模板格式" prop="templateFormat">
          <el-select v-model="form.templateFormat" placeholder="请选择模板格式">
            <el-option label="HTML" value="HTML" />
            <el-option label="DOCX" value="DOCX" />
            <el-option label="PDF" value="PDF" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio label="启用">启用</el-radio>
            <el-radio label="禁用">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 上传证书模板对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="500px" append-to-body>
      <el-form ref="uploadForm" :model="upload.form" :rules="upload.rules" label-width="80px">
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="upload.form.name" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="模板类型" prop="type">
          <el-select v-model="upload.form.type" placeholder="请选择模板类型">
            <el-option
              v-if="dict.type && dict.type.certificate_template_type"
              v-for="dict in dict.type.certificate_template_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="模板文件" prop="file">
          <el-upload
            class="upload-template"
            ref="upload"
            action="#" 
            :headers="upload.headers"
            :before-upload="beforeUpload"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            :auto-upload="false"
            :limit="1"
            :file-list="upload.fileList"
            drag
          >
            <el-icon><upload-filled /></el-icon>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <template #tip>
              <div class="el-upload__tip">只能上传word文档(docx)，且不超过10MB</div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="upload.form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitUpload">确 定</el-button>
          <el-button @click="cancelUpload">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { listTemplate, getTemplate, addTemplate, updateTemplate, delTemplate, previewTemplate } from "@/api/qep/certificate/template";
import { getToken } from "@/utils/auth";
import { getDicts } from '@/api/system/dict/data';
import request from '@/utils/request';
import { ArrowDown, Search, Refresh, Plus, Edit, Delete, Upload, View, Setting, Document, UploadFilled } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';

export default {
  name: "CertificateTemplate",
  components: {
    ArrowDown,
    Search, 
    Refresh, 
    Plus, 
    Edit, 
    Delete, 
    Upload,
    UploadFilled,
    View,
    Setting,
    Document
  },
  dicts: ['certificate_template_type'],
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 证书模板表格数据
      templateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 字典数据
      dict: {
        type: {}
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        type: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "模板名称不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "模板类型不能为空", trigger: "change" }
        ],
        templateFormat: [
          { required: true, message: "模板格式不能为空", trigger: "change" }
        ]
      },
      // 上传参数
      upload: {
        open: false,
        title: "上传证书模板",
        headers: { Authorization: "Bearer " + getToken() },
        // 注意：此action路径已不再使用，现在通过API函数直接上传文件
        action: "#",
        fileList: [],
        hasFile: false, // 添加文件标志
        uploadFile: null, // 存储选择的文件
        form: {
          name: undefined,
          type: undefined,
          remark: undefined
        },
        rules: {
          name: [
            { required: true, message: "模板名称不能为空", trigger: "blur" }
          ],
          type: [
            { required: true, message: "模板类型不能为空", trigger: "change" }
          ]
          // 移除file字段验证，改为在提交时手动检查
        }
      }
    };
  },
  created() {
    try {
      console.log("正在初始化证书模板页面...");
      // 手动加载字典数据
      this.loadDictData();
      // 获取列表数据
      this.getList();
    } catch (error) {
      console.error("初始化页面错误:", error);
      this.$message.error("初始化证书模板页面时遇到问题，请刷新页面重试");
    }
  },
  beforeDestroy() {
    // 清理DOM引用或事件监听器
    console.log("Certificate template component is being destroyed");
  },
  errorCaptured(err, vm, info) {
    console.error(`Error captured in certificate template component: ${err}, Info: ${info}`);
    // 返回false以防止错误继续传播
    return false;
  },
  methods: {
    /**
     * 加载字典数据
     */
    loadDictData() {
      console.log("开始加载字典数据...");
      getDicts("certificate_template_type").then(response => {
        console.log("字典数据响应:", response);
        if (response && response.data) {
          const dictData = response.data.map(p => ({ 
            label: p.dictLabel, 
            value: p.dictValue, 
            elTagType: p.listClass, 
            cssClass: p.cssClass 
          }));
          
          // 设置字典数据 - 直接赋值而不是使用$set
          this.dict.type.certificate_template_type = dictData;
          console.log("字典数据加载成功:", dictData);
        } else {
          console.warn("字典API返回的数据为空");
          // 如果后端暂时没有数据，设置一些默认选项
          const defaultOptions = [
            { label: '质量证明书', value: 'quality_certificate', elTagType: 'info', cssClass: '' },
            { label: '合格证', value: 'conformity_certificate', elTagType: 'success', cssClass: '' },
            { label: '检验报告', value: 'inspection_report', elTagType: 'warning', cssClass: '' }
          ];
          this.dict.type.certificate_template_type = defaultOptions;
          console.log("使用默认字典数据:", defaultOptions);
    }
  }).catch(error => {
        console.error("加载字典数据失败:", error);
        // 设置默认选项防止页面出错
        const defaultOptions = [
          { label: '质量证明书', value: 'quality_certificate', elTagType: 'info', cssClass: '' },
          { label: '合格证', value: 'conformity_certificate', elTagType: 'success', cssClass: '' },
          { label: '检验报告', value: 'inspection_report', elTagType: 'warning', cssClass: '' }
        ];
        this.dict.type.certificate_template_type = defaultOptions;
        // 使用Element Plus的消息提示方式
        ElMessage.warning("加载字典数据失败，已使用默认选项");
      });
    },
    
    /**
     * 确保字典数据已加载
     */
    ensureDictDataLoaded() {
      // 确保certificate_template_type字典数据已加载
      if (!this.dict.type.certificate_template_type) {
        this.loadDictData();
      }
    },
    /** 查询证书模板列表 */
    getList() {
      this.loading = true;
      try {
        listTemplate(this.queryParams).then(response => {
          this.templateList = response.rows;
          this.total = response.total;
          this.loading = false;
        }).catch(error => {
          console.error("Failed to get template list:", error);
          this.loading = false;
          this.$message.error("获取模板列表失败，请刷新页面重试");
        });
      } catch (error) {
        console.error("Error in getList:", error);
        this.loading = false;
        this.$message.error("获取模板列表时发生错误");
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        type: undefined,
        templateFormat: 'HTML',
        status: '启用',
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加证书模板";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids[0];
      getTemplate(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改证书模板";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTemplate(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTemplate(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除证书模板编号为"' + ids + '"的数据项？').then(function() {
        return delTemplate(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 更改状态操作 */
    handleStatusChange(row) {
      let text = row.status === "启用" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.name + '"模板吗？').then(function() {
        return updateTemplate(row);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.status = row.status === "启用" ? "禁用" : "启用";
      });
    },
    /** 上传按钮操作 */
    handleUpload() {
      this.upload.form = {
  name: undefined,
  type: undefined,
        remark: undefined
      };
      // 重置文件状态
      this.upload.fileList = [];
      this.upload.hasFile = false;
      this.upload.uploadFile = null;
      this.upload.open = true;
      
      // 确保在下一个事件循环中DOM已更新
      this.$nextTick(() => {
        if (this.$refs.upload) {
          this.$refs.upload.clearFiles();
        }
      });
    },
    // 处理文件选择变更
    handleFileChange(file, fileList) {
      console.log('文件变更:', file, fileList);
      // 保存选择的文件
      this.upload.hasFile = fileList.length > 0;
      this.upload.uploadFile = fileList.length > 0 ? file : null;
      this.upload.fileList = fileList;
    },
    
    // 处理文件移除
    handleFileRemove(file, fileList) {
      console.log('文件移除:', file, fileList);
      this.upload.hasFile = fileList.length > 0;
      this.upload.uploadFile = fileList.length > 0 ? fileList[0] : null;
      this.upload.fileList = fileList;
    },
    
    // 文件上传中处理
    handleFileUploadProgress() {
      this.upload.loading = true;
    },

    // 文件上传成功处理
    handleUploadSuccess(res, file) {
      this.upload.open = false;
      this.upload.loading = false;
      if (res.code === 200) {
        this.getList();
        this.$modal.msgSuccess("上传成功");
      } else {
        this.$modal.msgError("上传失败：" + res.msg);
      }
    },
    // 文件上传失败处理
    handleUploadError() {
      this.upload.loading = false;
      this.$modal.msgError("上传失败");
    },
    // 文件上传前的处理
    beforeUpload(file) {
      // 验证文件类型
      const isDocx = file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
      if (!isDocx) {
        this.$modal.msgError('上传文件只能是docx格式!');
        return false;
      }
      // 验证文件大小
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isLt10M) {
        this.$modal.msgError('上传文件大小不能超过 10MB!');
        return false;
      }
      return true;
    },
    // 提交上传表单
    submitUpload() {
      this.$refs["uploadForm"].validate(valid => {
        if (valid) {
          // 检查是否有选择文件
          if (!this.upload.hasFile || !this.upload.uploadFile) {
            this.$modal.msgError("请选择要上传的文件");
            return;
          }
          
          try {
            // 显示加载指示器
            this.upload.loading = true;
            
            // 获取上传的文件
            const file = this.upload.uploadFile.raw || this.upload.uploadFile;
            
            // 使用导入的API函数
            import('@/api/qep/certificate/template').then(api => {
              // 创建表单数据
              const formData = new FormData();
              formData.append('file', file);
              formData.append('name', this.upload.form.name);
              formData.append('type', this.upload.form.type);
              formData.append('remark', this.upload.form.remark || '');
              
              api.uploadTemplateFile(formData).then(response => {
                // 处理响应
                this.upload.open = false;
                this.upload.loading = false;
                
                // 如果成功，刷新列表并显示成功消息
                if (response.code === 200) {
                  this.getList();
                  this.$modal.msgSuccess("上传成功");
                } else {
                  this.$modal.msgError("上传失败：" + (response.msg || '未知错误'));
                }
              }).catch(error => {
                console.error("上传失败:", error);
                this.upload.loading = false;
                this.$modal.msgError("上传失败：" + (error.response?.data?.msg || error.message || '服务器错误'));
              });
            }).catch(error => {
              console.error("导入API模块失败:", error);
              this.upload.loading = false;
              this.$modal.msgError("系统错误，无法加载上传模块");
            });
          } catch (error) {
            console.error("表单处理错误:", error);
            this.$modal.msgError("表单处理错误：" + error.message);
            this.upload.loading = false;
          }
        }
      });
    },
    // 取消上传
    cancelUpload() {
      this.upload.open = false;
      // 重置文件状态
      this.upload.fileList = [];
      this.upload.hasFile = false;
      this.upload.uploadFile = null;
      
      if (this.$refs.upload) {
        this.$refs.upload.clearFiles();
      }
    },
    // 下拉菜单处理
    handleCommand(command, row) {
      switch (command) {
        case 'template-editor':
          this.handleTemplateEditor(row);
          break;
        case 'variables':
          this.handleVariables(row);
          break;
        default:
          break;
      }
    },
    // 处理模板编辑
    handleTemplateEditor(row) {
      this.$router.push({ path: '/certificate/template/template-editor', query: { id: row.id } });
    },
    // 处理变量
    handleVariables(row) {
      this.$router.push({ path: '/certificate/template/variables', query: { id: row.id } });
    }
  }
};
</script>

<style scoped>
.app-container {
  padding: 20px;
  margin-top: 0;
}
.upload-template .el-upload {
  width: 100%;
}
.el-upload--text {
  border: 1px dashed #d9d9d9 !important;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100%;
}
.el-upload--text:hover {
  border-color: #409eff !important;
}
</style> 